/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ies.domain.model.repository.util;


import com.ies.domain.model.util.ModelInterface;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author gustavo
 */
public abstract class AbstractFacade<T> {

    private Class<T> entityClass;
    protected Boolean carregaRelacionamentos = false;
    

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected static EntityManager getEntityManager() {
        return EntityManagerFactoryPool.getInstance().getEmf().createEntityManager();
    }

    public void create(T entity) {
        EntityManager entityManager = getEntityManager();
        try {
            entityManager.getTransaction().begin();
            entityManager.persist(entity);
            entityManager.getTransaction().commit();
        } catch (Exception ex) {
            Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
        } finally {
            entityManager.close();
        }

    }

    public void edit(T entity) {
        EntityManager entityManager = getEntityManager();
        try {
            entityManager.getTransaction().begin();
            entityManager.merge(entity);
            entityManager.getTransaction().commit();
        } catch (Exception ex) {
            Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
        } finally {
            entityManager.close();
        }
    }

    public void remove(T entity) {
        EntityManager entityManager = getEntityManager();
        try {
            entityManager.getTransaction().begin();
            entity = entityManager.find(entityClass, ((ModelInterface)entity).getId());
            entityManager.remove(entity);
            entityManager.flush();
            entityManager.getTransaction().commit();
        } catch (Exception ex) {
            Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
        } finally {
            entityManager.close();
        }
    }

    public T find(Object id) {
        EntityManager entityManager = getEntityManager();
        try {
            T objeto = null;
            objeto = entityManager.find(entityClass, id);
            if(carregaRelacionamentos){
                carregaLazy(objeto);
            }
            return objeto;
        } catch (Exception ex) {
            Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
            return null;
        } finally {
            entityManager.close();
        }
    }

    public List<T> findAll() {
        EntityManager entityManager = getEntityManager();
        try {
             List<T> lista = new ArrayList<T>();
            StringBuffer sql = new StringBuffer("SELECT obj FROM " + entityClass.getSimpleName() + " obj ");
            Query query = entityManager.createQuery(sql.toString());
            lista = query.getResultList();
            if(carregaRelacionamentos){
                for (T objeto : lista) {
                    carregaLazy(objeto);
                }
            }
            return lista;
        } catch (Exception ex) {
            Logger.getLogger(ex.getLocalizedMessage(), ex.getLocalizedMessage());
            Logger.getLogger(this.getClass().getSimpleName()).log(Level.SEVERE, null, ex);
            return null;
        } finally {
            entityManager.close();
        }
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public Long count() {
        EntityManager entityManager = getEntityManager();
        String sql = new String("SELECT COUNT(obj) FROM " + entityClass.getSimpleName() + " obj ");
        Query query = entityManager.createQuery(sql);
        return (Long)query.getSingleResult();
    }

    public  T carregaLazy(T object){
       return object;
    }
    
    
     public Class<T> getEntityClass() {
        return entityClass;
    }

    public void setEntityClass(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public Boolean getCarregaRelacionamentos() {
        return carregaRelacionamentos;
    }

    public void setCarregaRelacionamentos(Boolean carregaRelacionamentos) {
        this.carregaRelacionamentos = carregaRelacionamentos;
    }

    
    
    
}
